<template>
    <n-data-table
        :columns="config.columns"
        :loading="loading"
        :data="data"
        :bordered="false"
    />
</template>

<script setup lang="ts">
import { onMounted, PropType, unref } from 'vue'
import { TableConfig } from '../types'
import { useRequest } from 'vue-request'
import { useMessage } from 'naive-ui'

type DataType = any

const props = defineProps({
    config: {
        type: Object as PropType<TableConfig<DataType>>,
        required: true
    }
})

const message = useMessage()

// 请求数据
const { loading, data, run } = useRequest(props.config.service!, {
    manual: true,
    ready: props.config?.ready,
    onError(error) {
        message.error(error.message)
    }
})

onMounted(() => {
    const auto = props.config.auto
    if (
        (props.config.service && typeof auto === 'undefined') ||
        auto === true
    ) {
        run(unref(props.config.params || {}))
    }
})

defineExpose({
    run: (params?: any) =>
        run(Object.assign({}, unref(props.config.params || {}), params))
})
</script>
